import React,{forwardRef,useImperativeHandle, useState,useRef} from "react";
import {Button,Input,Tag,Popover,Form} from 'antd'
import LlxTable from 'components/LlxTable'
import {SortableHandle } from 'react-sortable-hoc';
import { MenuOutlined } from '@ant-design/icons';
import UploadPicture from 'components/Upload/index'
import AudioUpload from 'components/Upload/audio'
import UploadJson from 'components/Upload/json'
import EditJsonBook from "components/EditJsonBook";
import {connect} from 'react-redux'
import AddGame from 'components/AddNewGame'
import AddOrEditSubject from "components/AddOrEditSubject";
import PreviewSubject from 'components/LlxPreview/subject'
import EditSubject from 'components/EditSubjec'
import PreviewGame from 'components/LlxPreview/game'
import {getGraphDetailById,getSubjectInfo} from 'api/index'
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

const BookContent = forwardRef((props, ref) => {
  
  const {disabled,setDataSource,dataSource,id} = props


const [isModalVisible,setIsModalVisible] = useState(false)


useImperativeHandle(ref, () => ({
  dataSource
}));

const SubjectContent = (props) => {

  
  const subjectType = props.subjectType
  const row = props.row
  const dictionaries = props.dictionaries
  const userName = props.userName


  const [addSubejct,setAddSubject] = useState(false)
  const [isModalVisibleEditSubject,setIsModalVisibleEditSubject] = useState(false)
  const [isModalVisibleAddGame,setIsModalVisibleAddGame] = useState(false)
  const [subjectPreviewGame,setSubjectPreviewGame] = useState(false)
  const [subjectPreview,setSubjectPreview] = useState(false)
  const game = useRef()
  const [subjectFormNew] = Form.useForm()
  const [subjectFormEdit] = Form.useForm()

  

  const previewSubejct = (value) => {
    setSubjectPreview(true)
  }
  const remove = () => {
    props.setNewSubject('','',row.id)
  }
  const previewGame = () => {
    setSubjectPreviewGame(true)
  }
  const editSubject = async () => {
   // 获取题目数据
   const res = await getSubjectInfo(row.subjectId)

   subjectFormEdit.setFieldsValue({
     ...res.result,
     type:[res.result.type+'',res.result.subjectType+''],
     label:res.result.labels?.map(i=>{
       return [i.labelCategoryId,i.id]
     }),
     examinationTypeId:res.result.examinationType?.map(i=>{
       return i.grammarId?i.grammarId:i.examinationTypeId
     })
   })

   setIsModalVisibleEditSubject(true)
  }
  const addSubject = () => {
    subjectFormNew.resetFields() //重置
    setAddSubject(true)
  }
  const addGame = () => {
    game.current.setDataSource([])

    game.current.form.resetFields()

    game.current.form.setFieldsValue({
      pictureUrl:row.pictureUrl,id:'',backgroundMusic:'',
      analysisAudio:'',
      analysisText: '',
      guideAudio: '',
      guideText:''
    })
    setIsModalVisibleAddGame(true)
  }
  const editGame = async() => {
    const res = await getGraphDetailById(row.subjectId)
    game.current.form.setFieldsValue(res.result)

    game.current.form.setFieldsValue({
      gameItems:res.result.gameCircleDTO?.map((i,j) => {
        return {
          answers: i.answers.map(item => {
            return {
              circleId: item.circleId,
              coordinate: JSON.parse(item.coordinate)
            }
          }),
          pictureUrl: i.pictureUrl,
          examination: i.examination,
          audioUrl: i.audioUrl,
          correctError: i.correctError,
          wordId: i.wordId,
          gameId: i.gameId,
          sort:j+1,
          id: i.id,
          interfereAudio: i.interfereAudio,
          interfereText: i.interfereText
        }
      })||[]
    })

    setIsModalVisibleAddGame(true)
  }
  const getSubjectId = (value) => {
    props.setNewSubject(value,'2',row.id)
  }
  const getSubjectGameId = (value) => {
    props.setNewGame(value,'1',row.id)
  }
  const getInfoFn = () => {

  }

const content = subjectType==='2'?<div>
  <Button onClick={previewSubejct} type={'link'} >预览</Button>
  <Button onClick={remove} type={'link'} >移除</Button>
  <Button onClick={editSubject}  type={'link'} >编辑</Button>
</div>:(
subjectType==='1'?<div>
  <Button onClick={previewGame}  type={'link'} >预览</Button>
  <Button  onClick={remove} type={'link'} >移除</Button>
  <Button onClick={editGame} type={'link'} >编辑</Button>
</div>:<div>
  <Button onClick={addSubject} type={'link'} >新建题目</Button>
  <Button onClick={addGame} type={'link'} >新建圈图</Button>
</div>
)

  

  return  <div>
    <Popover content={content} title="内容出题">
     
     {
       subjectType==='1'?<Tag className="content-tag" color="success">圈图题</Tag>:(subjectType==='2'?<Tag className="content-tag" color="success">题目</Tag>:<Tag className="content-tag" color="warning">未出题</Tag>)
     }
   </Popover>



    {/* 新增题目 */}
  <AddOrEditSubject getSubjectId={getSubjectId} getInfoFn={getInfoFn} sort={dataSource.length+1} globalOriginType={4}   paperBookId={''}  dictionaries={dictionaries} form={subjectFormNew}  setIsModalVisible={setAddSubject} isModalVisible={addSubejct}></AddOrEditSubject>
  {/* 编辑题目 */}
  <EditSubject getInfoFn={getInfoFn}  dictionaries={dictionaries} form={subjectFormEdit} isModalVisible={isModalVisibleEditSubject}  setIsModalVisible={setIsModalVisibleEditSubject} ></EditSubject>
  {/* 新增圈图 */}
  <AddGame  globalType={3} disabled getSubjectGameId={getSubjectGameId} ref={game} isModalVisible={isModalVisibleAddGame} setIsModalVisible={setIsModalVisibleAddGame} userName={userName} dictionaries={dictionaries}></AddGame>
  {/* 编辑圈图 */}

  {/* 预览题目 */}
  <PreviewSubject  id={row.subjectId} setIsModalVisible={setSubjectPreview} isModalVisible={subjectPreview} ></PreviewSubject>

  {/* 预览圈图 */}
  <PreviewGame  id={row.subjectId + '?' + Math.random()*100} setIsModalVisible={setSubjectPreviewGame} isModalVisible={subjectPreviewGame} ></PreviewGame>

  



  </div>
}

//表头配置信息
const columns = [
      {
        title: '排序',
        dataIndex: 'sort',
        width: 100,
        className: 'drag-visible',
        align: 'center',
        render: () => <DragHandle />,
      },
      {title: '图片', dataIndex: 'pictureUrl',key: 'pictureUrl', align: 'center',render: (text, record) => {
        return <div className="operate_link_group">
          <UploadPicture disabled={disabled} pictureUrl={record.pictureUrl} setPhoto={(value)=>record.pictureUrl=value}></UploadPicture>
       </div>
      }},
       {title: '音频',width: 250, dataIndex: 'audioUrl',key: 'audioUrl', align: 'center',render: (text, record) => {
      return <div className="operate_link_group" >
        <AudioUpload disabled={disabled} audio={record.audioUrl} style={{marginLeft:'20px'}} setAudio={value=>record.audioUrl=value}></AudioUpload>
     </div>
       }},
       {title: '文字', dataIndex: 'content',key: 'content', align: 'center',render: (text, record) => {
       return <div className="operate_link_group">
          <Input disabled={disabled} defaultValue={record.content} placeholder={'请输入文字'} allowClear onChange={e=>record.content = e.target.value}/>
      </div>
       }}, {title: '字幕',width: 250, dataIndex: 'captionUrl',key: 'captionUrl', align: 'center',render: (text, record) => {
       return <div className="operate_link_group"  >
        <UploadJson disabled={disabled} captionUrl={record.captionUrl} style={{marginLeft:'20px'}} setJson={(value)=>record.captionUrl=value}></UploadJson>
      </div>
       }},
       {title: '出题', width:80,dataIndex: 'subject',key: 'subject', align: 'center',render: (text, record) => {
        return <div className="operate_link_group"  >
               <SubjectContent setNewGame={setNewGame} setNewSubject={setNewSubject} dictionaries={props.dictionaries} userName={props.userInfo.user.userName} row={record} id={record.subjectId} subjectType={record.subjectType}></SubjectContent>
       </div>
        }}
       ,{title: '编辑',width: 100,dataIndex: 'active',key: 'active', align: 'center',render: (text, record) => {
      return <div className="operate_link_group">
       <Button type={'link'} disabled={disabled} onClick={()=>removeContent(record.sort)} >移除</Button>
     </div>
       }}
]



const removeContent = (sort) => {
  setDataSource(value=>value.filter(i=>i.sort!==sort))
}

const setNewSubject = (a,b,c) => {
  const item = {
    id: c,
    subjectId: a,
    subjectType: b * 1
  }
  props.setNewSubjectFn(item)
}
const setNewGame = (a,b,c) => {
  const item = {
    id: c,
    subjectId: a,
    subjectType: b * 1
  }
  props.setNewGameFn(item)
}

  
  return <>

  <div>

<LlxTable
     selectedRowShow={false}
     height={300}
     components={true}
     paginationHide={true}
     setDataSource={setDataSource}
     columns={columns}
     dataSource={dataSource}/>
  </div>

  <EditJsonBook isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible} id={id}></EditJsonBook>

  </>
})


export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},null)(BookContent)